<?php


namespace app\admin\controller;


use app\admin\common\Export;
use app\admin\library\Auth;
use app\admin\model\Alternative;
use app\admin\model\Applies;
use app\admin\model\ApplyType;
use app\admin\model\Approval;
use app\admin\model\ArchiveAppendix;
use app\admin\model\Archives;
use app\admin\model\ArchiveType;
use app\admin\model\AuthGroup;
use app\admin\model\Blessing;
use app\admin\model\GatherTypeImage;
use app\admin\model\Item;
use app\admin\model\WorkRun;
use app\BaseController;
use fast\Tree;
use http\Message\Body;
use think\facade\Route;
use think\facade\View;
use think\Request;

class Administration extends BaseController
{
    /**
     * @var \app\admin\model\Admin
     */
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];
    protected $group = [];
    protected $groupList = "";
    protected $vacation = null;
    protected $juese = null;

    public function initialize()
    {

        parent::initialize();
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        $this->groupList = collection(AuthGroup::select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                $temp[$n['id']] = $n['name'];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result = $temp;
                $this->juese = $n['name'];
            }
            $groupdata = $result;
        }
        $this->group = $groupdata;
        $this->vacation = new \app\admin\model\Vacation();
        View::assign('group', $groupList);
    }

    //资源显示
    public function index(Request $request)
    {

        //where('id', 'in', $this->childrenAdminIds)->
        $model = \app\admin\model\Admin::with(['AuthGroupAccess' => ['AuthGroup']])->select();
        foreach ($model as $key => $value) {
            $pinjie = "";
            foreach ($value['AuthGroupAccess'] as $key1 => $v) {
                $pinjie = $v['AuthGroup']['name'] . ',';
            }
            $value['rules'] = rtrim($pinjie, ',');
            $value['birthday_num'] = \app\admin\model\Admin::Birthday($value['birthday'], $value['lunar']);
        }
        View::assign('model', $model);
        return View::fetch();
    }


    //考勤列表
    public function check(Request $request)
    {
        if ($request->isAjax()) {

        }
        return View::fetch('administration/check/index');
    }


    //休假管理
    public function vacation(Request $request)
    {

        $is_mobile = wp_is_mobile();
        if ($is_mobile == true) {
            $verify_type = 1; //手机
        } else {
            $verify_type = 2; //PC
        }
        $alternative = Alternative::select();
        $where_auth = [];
        if ($this->juese != "综合运营部") {
            $where_auth[] = array("id", "in", $this->childrenAdminIds);
        }
        $admin = \app\admin\model\Admin::where($where_auth)->where('status', 1)->select();
        if ($request->isAjax()) {
            $admin_id = $request->param('admin_id');
            $where = array();
            if (!empty($admin_id)) {
                $where[] = array("admin_id", "=", $admin_id);
            }
            $where_auths = [];
            if ($this->juese != "综合运营部") {
                $where_auths[] = array("admin_id", "in", $this->childrenAdminIds);
            }
            $vacation = $this->vacation->where($where_auths)->where($where)->select();
            $new_data = [];
            $i = 0;
            foreach ($vacation as $key => $value) {

                $status = $this->status(($value['status']));
                $new_data[]['title'] = $status . '---' . '[' . $value['group_name'] . ']' . '-' . $value['username'] . '-' . $value['alternative_title'];
                $new_data[$i]['id'] = trim($value['id']);
                $new_data[$i]['start'] = trim($value['start_time']);
                $new_data[$i]['end'] = trim($value['end_time']);
                $new_data[$i]['color'] = $value['color'];
                $new_data[$i]['remark'] = $value['remark'];
                $new_data[$i]['status'] = $value['status'];
                $new_data[$i]['task_status'] = checkTaskStatus('vacations', $value['id']);
                $i++;
            }
            return json($new_data);
        }
        View::assign('alternative', $alternative);
        View::assign('admin', $admin);
        View::assign('verify_type', $verify_type);
        return View::fetch('administration/vacation/index');
    }

    //状态
    public function status($status)
    {
        switch (intval($status)) {
            case "0":
                return "保存中";
                break;
            case "1":
                return "流程中";
                break;
            case "2":
                return "审核通过";
                break;
            default: //-1
                return "退回";
        }
    }

    //档案信息
    public function archives(Request $request)
    {
        $id = $request->param('admin_id');
        $admin = \app\admin\model\Admin::with(['Archives' => ['ArchiveAppendix']])->find($id);
        $new_arr = [];
        if (!empty($admin->Archives['ArchiveAppendix'])) {

            foreach ($admin->Archives['ArchiveAppendix'] as $k => $v) {
                $new_arr[]['id'] = $v['id'];
                $new_arr[$k]['type_id'] = $v['type_id'];
                $new_arr[$k]['path'] = $v['path'];
                $new_arr[$k]['path_arr'] = explode(',', $v['path']);
                $new_arr[$k]['type_id'] = $v['type_id'];
            }
            $admin['new_arr'] = $new_arr;
        } else {
            $admin['new_arr'] = $new_arr;
        }
        $archive_type = ArchiveType::where('status', 1)->select();
        if ($request->isAjax()) {
            $data = $request->param();
            unset($data['birthday'], $data['mobile'], $data['email']);
            $admin_data = $request->only(['birthday', 'mobile', 'email']);
            $res_find = Archives::where('admin_id', $data['admin_id'])->find();
            $res = Archives::findOrEmpty($res_find['id']);
            $type_id = array_filter($request->param('type_id')); //类别id
            $path = array_filter($request->param('pic_imgs')); //文件路径
            if (!$res->isEmpty()) {
                $data['id'] = $res['id'];
                $res_del = ArchiveAppendix::where(['admin_id' => $data['admin_id'], 'archive_id' => $res['id']])->select();
                if (!empty($res_del)) {
                    foreach ($res_del as $k1 => $v1) {
                        ArchiveAppendix::destroy(($v1['id']));
                    }
                }
                if (!empty($type_id) && !empty($path)) {
                    foreach ($type_id as $key => $value) {
                        ArchiveAppendix::create([
                            'admin_id' => $data['admin_id'],
                            'path' => $path[$key],
                            'archive_id' => $res['id'],
                            'type_id' => $value
                        ]);
                    }
                }
                $result = Archives::update($data);
            } else {
                if (!empty($type_id) && !empty($path)) {
                    foreach ($type_id as $key => $value) {
                        ArchiveAppendix::create([
                            'admin_id' => $data['admin_id'],
                            'path' => ltrim($path[$key]),
//                            'archive_id' => $result->id,
                            'type_id' => $value
                        ]);
                    }
                }
                $result = Archives::create($data);
                if ($result) {

                }
            }
            if ($result) {
                $admin_data['id'] = $data['admin_id'];
                \app\admin\model\Admin::update($admin_data);
            }
            return json(['code' => 200, 'url' => '', 'msg' => '成功！']);
        }
        if (count($admin['new_arr']) == 0) {
            unset($admin['new_arr']);
        }

        View::assign('admin', $admin);
        View::assign('archive_type', $archive_type);
        return View::fetch();
    }

    //生日日历
    public function BirthdayCalendar(Request $request)
    {
        if ($request->isAjax()) {
            $admin = \app\admin\model\Admin::where('id', 'in', $this->childrenAdminIds)->where('status', 1)->select();
            $new_data = [];
            $i = 0;
            foreach ($admin as $key => $value) {
                if (!empty($value['birthday'])) {
                    if (strpos($value['birthday'], '/') !== false) {
                        $avator = str_replace('/', '-', $value['birthday']);
                    } else {
                        $avator = $value['birthday'];
                    }
                    if ($value['lunar'] == 1) {
                        $day = explode('-', $avator);
                        $brithday = $this->lunar->convertLunarToSolar(date('Y'), $day[0], $day[1]);
                    } else {
                        $brithday = date("Y-m-d", strtotime(date('Y') . '-' . $avator));
                    }
                    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
                    $color = '#' . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)];
                    $new_data[]['title'] = $value['nickname'] . '-' . (($value['lunar'] ? 0 : 1) ? '阳历' : '农历') . '-' . date('Y') . '-' . $avator;
                    $new_data[$i]['start'] = $brithday;
                    $new_data[$i]['color'] = $color;
                    $i++;
                }
            }

            return json($new_data);
        }
        return View::fetch();
    }

    //表格转换
    public function ChangeTable(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');

            $result = \app\admin\model\Admin::with(['AuthGroupAccess' => ['AuthGroup']])->where('id', 'in', $this->childrenAdminIds)->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                $pinjie = "";
                foreach ($item['AuthGroupAccess'] as $k => $v) {
                    $pinjie .= $v['AuthGroup']['name'] . ',';
                }
                $item['birthday_num'] = \app\admin\model\Admin::Birthday($item['birthday'], $item['lunar']);
                $item['rules'] = rtrim($pinjie, ',');
            })->toArray();

            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        return View::fetch();
    }

    //申请管理
    public function apply(Request $request)
    {
        $arr = ['id' => 0, 'name' => '全部'];
        $apply_type = ApplyType::field('id,name')->where('status', 1)->select()->toArray();
        array_unshift($apply_type, $arr);
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $where = array();
            $id = $request->param('id');
            if ($id != 0) {
                $where[] = array("type_id", "=", $id);
            }

            if ($this->juese != "财务" && $this->juese != "出纳") {
                $where[] = array("admin_id", "in", $this->childrenAdminIds);
            }
            $result = Applies::with(['appliyType','money'])->where($where)->order('create_time desc')->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                $item['task_status'] = checkTaskStatus('journals', $item['id']);
                if ($item['admin_id'] == $this->auth->id) {
                    $item['edit_auth'] = 1;
                } else {
                    $item['edit_auth'] = 2;
                }
                return $item;
            })->toArray();
            foreach ($result['data'] as $key => $value) {
                $result['data'][$key]['status_type'] = $this->status($value['status']);
                $result['data'][$key]['task_status'] = checkTaskStatus('applies', $value['id']);
            }
            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        View::assign('apply_type', $apply_type);
        return View::fetch('administration/apply/index');
    }

    //祝福管理
    public function blessing(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $result = Blessing::paginate($limit, false, ['page' => $page])->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        return View::fetch('administration/blessing/index');
    }

    //导出
    public function download(Request $request)
    {
        if ($request->isAjax()) {
            $where = array();
            if (!empty($request->post('ids'))) {
                $where[] = array("id", "in", $request->post('ids'));
            }

            $xlsName = "通讯录" . time();
            $xlsCell = array(
                array('id', 'ID'),
                array('username', '用户名'),
                array('nickname', '昵称'),
                array('rules', '所属组别'),
                array('mobile', '手机号'),
                array('email', '邮箱'),
                array('birthday_num', '生日'),
            );
            $result = \app\admin\model\Admin::with(['AuthGroupAccess' => ['AuthGroup']])->where($where)->field('id,username,nickname,mobile,email,birthday,lunar')->select();
            foreach ($result as $key => $value) {
                $pinjie = "";
                foreach ($value['AuthGroupAccess'] as $k => $v) {
                    $pinjie .= $v['AuthGroup']['name'] . ',';
                }
                $value['birthday_num'] = \app\admin\model\Admin::Birthday($value['birthday'], $value['lunar']);
                $value['rules'] = rtrim($pinjie, ',');
            }
            $export = new Export();
            $url = $export->exportExcel($xlsName, $xlsCell, $result);
            echo json_encode($url);
            exit();
        }
    }

    //文件上传
    public function upload(Request $request)
    {
        $files = $request->file();
        $id = $request->param('id');
        $savename = [];
        $update_admin = [];
        foreach ($files as $key => $file) {
            if (!empty($id)) {
                $update_admin = [
                    'id' => $id,
                    'portrait' => '/storage/' . \think\facade\Filesystem::disk('public')->putFile('admin_portrait', $file, 'uniqid')
                ];
            }
            $savename['src'] = \think\facade\Filesystem::disk('public')->putFile('admin_portrait', $file, 'uniqid'); # code...
            $savename['name'] = $file->getOriginalName();
        }
        if (!empty($update_admin)) {
            \app\admin\model\Admin::update($update_admin);
        }
        $data = [
            "code" => 0,
            'msg' => '',
            "data" => $savename,
        ];
        return json($data);
    }

    //审批管理测试
    public function approval(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');

            $result = Approval::with(['admin' => ['AuthGroups']])->order('id', 'desc')->paginate($limit, false, ['page' => $page])->toArray();
//            foreach ($result['data'] as $key => $value) {
//                $res = WorkRun::searchTable($value['from_table'], $value['from_id']);
//                $result['data'][$key]['group_name'] = $res['group_name'] ?? 'unknown';
//                $result['data'][$key]['username'] = $value['admin']['nickname'] ?? $value['admin']['username'];
//                $result['data'][$key]['status_table'] = $res['status'] ?? 1;
////                $result['data'][$key]['status'] = $this->status($res['status']);
////
////                $abc = Wf::btn($value['from_id'], $value['from_table'], $res['status']);
////
////                $result['data'][$key]['btn'] = " <a class=\"layui-btn " . $abc['class'] . " layui-btn-xs\" lay-event=\"" . $abc['lay'] . "\"><i class=\"layui-icon layui-icon-read\"></i>" . $abc['title'] . "[" . $abc['username'] . "]</a>";
//            }

            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        $limit = $request->param('limit');
        //获取当前页数
        $page = $request->param('page');
        //    protected $childrenGroupIds = [];
        //    protected $childrenAdminIds = [];
//           halt( $this->auth->getGroups(Auth::instance()->id));
//        $result = WorkRun::with(['admin','process'=>function($query){
//            $query->where('auto_sponsor_ids',Auth::instance()->id);
//        }])->order('id', 'desc')->select()->filter(function ($workRun){
//            if (!is_null($workRun->process)){
//                return true;
//            }
//        });


        $result = Approval::with(['admin' => ['AuthGroups'], 'typeName'])->order('id', 'desc')->paginate($limit, false, ['page' => $page])->toArray();
        foreach ($result['data'] as $key => $value) {
            $group = $this->auth->getGroups($value['uid']);
            foreach ($group as $k => $v) {
                $admin_list = $this->getParent($this->groupList, $v['group_id']);
                if (count($admin_list) == 0) {
                    if ($this->auth->dept_id == $value['uid']) {
                        $result['data'][$key]['sh_status'] = 1; //可以审核
                    } else {
                        $result['data'][$key]['sh_status'] = 2; //无法审核
                    }
                }
                foreach ($admin_list as $key1 => $value1) {
                    if ($this->auth->dept_id == $value1['id']) {
                        $result['data'][$key]['sh_status'] = 1; //可以审核
                    } else {
                        $result['data'][$key]['sh_status'] = 2; //无法审核
                    }
                }
            }
            $res = WorkRun::searchTable($value['from_table'], $value['from_id']);
            $result['data'][$key]['group_name'] = $value['admin']['AuthGroups']['name'] ?? "unknown";
            $result['data'][$key]['username'] = $value['admin']['nickname'] ?? $value['admin']['username'];
            $result['data'][$key]['status_table'] = $res['status'] ?? 1;
            $result['data'][$key]['type_name'] = $value['typeName']['name'] ?? "休假";
        }
        View::assign('list', $result['data']);
        return View::fetch();
    }

    /**
     * 得到当前位置所有父辈数组
     * @param int
     * @param bool $withself 是否包含自己
     * @return array
     */
    public function getParent($arr, $myid)
    {
        $pid = 0;
        $newarr = [];
        foreach ($arr as $value) {
            if (!isset($value['id'])) {
                continue;
            }
            if ($value['id'] == $myid) {
                $pid = $value['pid'];
                break;
            }
        }
        if ($pid) {
            foreach ($arr as $value) {
                if ($value['id'] == $pid) {
                    $newarr[] = $value;
                    break;
                }
            }
        }
        return $newarr;
    }

}
